﻿Namespace DoFactory.GangOfFour.Chain.Structural

    ''' <summary>
    ''' MainApp startup class for Structural
    ''' Chain of Responsibility Design Pattern.
    ''' </summary>
    Public Class MainApp

        ''' <summary>
        ''' Entry point into console application.
        ''' </summary>
        Public Shared Sub Main()

            ' Setup Chain of Responsibility
            Dim h1 As Handler = New ConcreteHandler1()
            Dim h2 As Handler = New ConcreteHandler2()
            Dim h3 As Handler = New ConcreteHandler3()

            h1.SetSuccessor(h2)
            h2.SetSuccessor(h3)

            ' Generate and process request
            Dim requests As Integer() = {2, 5, 14, 22, 18, 3, _
             27, 20}

            For Each request As Integer In requests
                h1.HandleRequest(request)
            Next

        End Sub

    End Class

    ''' <summary>
    ''' The 'Handler' abstract class
    ''' </summary>
    MustInherit Class Handler

        Protected successor As Handler

        Public Sub SetSuccessor(ByVal successor As Handler)
            Me.successor = successor
        End Sub

        Public MustOverride Sub HandleRequest(ByVal request As Integer)

    End Class

    ''' <summary>
    ''' The 'ConcreteHandler1' class
    ''' </summary>
    Class ConcreteHandler1
        Inherits Handler

        Public Overrides Sub HandleRequest(ByVal request As Integer)
            If request >= 0 AndAlso request < 10 Then
                Console.WriteLine("{0} handled request {1}", Me.[GetType]().Name, request)
            ElseIf successor IsNot Nothing Then
                successor.HandleRequest(request)
            End If
        End Sub

    End Class

    ''' <summary>
    ''' The 'ConcreteHandler2' class
    ''' </summary>
    Class ConcreteHandler2
        Inherits Handler

        Public Overrides Sub HandleRequest(ByVal request As Integer)
            If request >= 10 AndAlso request < 20 Then
                Console.WriteLine("{0} handled request {1}", Me.[GetType]().Name, request)
            ElseIf successor IsNot Nothing Then
                successor.HandleRequest(request)
            End If
        End Sub

    End Class

    ''' <summary>
    ''' The 'ConcreteHandler3' class
    ''' </summary>
    Class ConcreteHandler3
        Inherits Handler

        Public Overrides Sub HandleRequest(ByVal request As Integer)
            If request >= 20 AndAlso request < 30 Then
                Console.WriteLine("{0} handled request {1}", Me.[GetType]().Name, request)
            ElseIf successor IsNot Nothing Then
                successor.HandleRequest(request)
            End If
        End Sub

    End Class

End Namespace
